package cn.kgc.controller;

import cn.kgc.entity.Comment;
import cn.kgc.entity.GameNum;
import cn.kgc.entity.Shop;
import cn.kgc.entity.UserB;
import cn.kgc.service.CommentService;
import cn.kgc.service.userService;
import cn.kgc.util.PageBeanHelper;
import cn.kgc.entity.GameNum;
import cn.kgc.entity.Shop;
import cn.kgc.entity.UserB;
import cn.kgc.service.userService;
import cn.kgc.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 蒿雨
 * @create 2021-11-15 9:59
 */
@Controller
@RequestMapping("/dev")
public class DevController {
    @Resource
    private CommentService commentService;

    @Resource
    private userService userService;

    //删除订单
    @RequestMapping("/deleteOrders")
    @ResponseBody
    public String deleteOrders(Integer userId, Integer shopId) {
        boolean flag = userService.deleteOrders(userId, shopId);
        return JSON.toJSONString(flag);
    }

    @RequestMapping("/deletescShop")
    @ResponseBody
    public String deletescShop(Integer userId, Integer shopId) {
        boolean flag = userService.deleteSCShop(userId, shopId);
        return JSON.toJSONString(flag);
    }

    @RequestMapping("/UserCenterscShop")
    @ResponseBody
    public String UserCenterscShop(Integer userId, Integer shopId) {
        int flag = userService.scShop(userId, shopId);
        return JSON.toJSONString(flag);
    }

    @RequestMapping("/UserCenterSelect")
    @ResponseBody
    public String UserCenterSelect(HttpSession session) {
        UserB userB = (UserB) session.getAttribute("user");
        String uName = userB.getuName();
        System.out.println(122);
        System.out.println(userB.toString());
        try {
            if (uName != null || !uName.equals("")) {
//                userService us = new userServiceImpl();
//                UserB u = userService.getUserByName(uName);
                return JSON.toJSONString(userB);
            } else {
                return JSON.toJSONString(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping("/uploadPic")
    public String uploadPic(@RequestParam(value = "file") MultipartFile multipartFile, HttpSession session) {
        //上升作用域
        String idPicPathError = "";
        String newFileName = "";
        String fileUploadPath = "";
        //1.进行准备工作
        //获取文件夹的绝对路径
        fileUploadPath = session.getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
        //获取文件名
        String fileName = multipartFile.getOriginalFilename();
        //判断文件大小
        if (multipartFile.getSize() > 5000000) {
            idPicPathError = "上传的文件超过限制大小";
            return "redirect:/tj/userCenter";
        }
        //前后缀
        String prefix = fileName.substring(0, fileName.indexOf("."));
        String suffix = fileName.substring(fileName.indexOf(".") + 1);

        //判断文件类型
        List<String> list = new ArrayList<>();
        list.add("jpg");
        list.add("jpeg");
        list.add("png");
        if (!list.contains(suffix)) {
            idPicPathError = "上传文件不符合格式!";
            return "redirect:/tj/userCenter";
        }
        //定义上传的文件名
        newFileName = prefix + (int) (Math.random() * (100000 - 10000) + 10000) + "" + System.currentTimeMillis() + "." + suffix;
        //创建文件上传容器(上传的绝对路径,文件名)
        File file = new File(fileUploadPath, newFileName);
        if (!file.exists()) {
            file.mkdirs();//创建文件夹
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return "redirect:/tj/userCenter";
        }
        UserB userb = (UserB) session.getAttribute("user");
        Integer id = userb.getId();
        String pic = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + newFileName;
        boolean flag = userService.uploadHead(id, pic);
        return "redirect:/tj/userCenter";

    }


    @RequestMapping("/CheckUserNameServlet")
    @ResponseBody
    public String CheckUserNameServlet(String userName) {
        boolean flag = userService.checkUserName(userName);
        return JSON.toJSONString(flag);
    }

    @RequestMapping("/CheckUNameServlet")
    @ResponseBody
    public String CheckUNameServlet(String uName) {
        boolean flag = userService.checkUName(uName);
        return JSON.toJSONString(flag);
    }


    @RequestMapping("/selectShop")
    @ResponseBody
    public String selectShop(Integer currentPage, Integer pageSize, String name1) {

        List<Shop> shops = null;
        Integer startPage = (currentPage - 1) * pageSize;
        //jedis缓存
//        //声明变量
//        Jedis jedis = RedisUtil.getJedis();
//        //判断缓存是否存在
//        if (!jedis.exists("shops" +name1+ startPage)) {
//            shops = userService.shopList(startPage, pageSize, name1.toString());
//            String list = JSON.toJSONString(shops);
//            //把集合压入缓存
//            jedis.set("shops" +name1+ startPage, list);
//        } else {
//            //json类型转换成集合类型
//            String list = jedis.get("shops" +name1+ startPage);
//            shops = JSON.parseObject(list, List.class);
//        }
        shops = userService.shopList(startPage, pageSize, name1.toString());
        return JSON.toJSONString(shops);
    }


    @RequestMapping("/TotalCountServlet")
    @ResponseBody
    public String TotalCountServlet(String name1) {
        System.out.println(name1);
        int count = userService.totalCount(name1.toString());
        return JSON.toJSONString(count);
    }

    @RequestMapping("/moCount")
    @ResponseBody
    public String moCount(String title) {
        int count = userService.moHuTotalCount(title.toString());
        System.out.println(count);
        return JSON.toJSONString(count);
    }

    @RequestMapping("/moList")
    @ResponseBody
    public String moList(Integer currentPage, Integer pageSize, String title) {
        //计算起始页
        Integer startPage = (currentPage - 1) * pageSize;
//        //上升作用域
//        List<Shop> shops = null;
//        //声明jedis对象
//        Jedis jedis = RedisUtil.getJedis();
//        System.out.println(title);
//        if (!jedis.exists("shopsmohu"+title+startPage)) {
//            System.out.println("开始缓存");
//            shops = userService.moHuList(startPage, pageSize, title.toString());
//            String list = JSON.toJSONString(shops);
//            jedis.set("shopsmohu"+title+startPage, list);
//        } else {
//            System.out.println("进入缓存");
//            String list = jedis.get("shopsmohu"+title+startPage);
//            shops = JSON.parseObject(list, List.class);
//        }

        List<Shop> shops = userService.moHuList(startPage, pageSize, title.toString());
        return JSON.toJSONString(shops);
    }

    @RequestMapping("/updataStatus")
    @ResponseBody
    public String updataStatus(Integer id, Integer status, String uName) {
        Shop shop = userService.updateShopStatus(id, status, uName);
        return JSON.toJSONString(shop);
    }


    @RequestMapping("/checkMoney")
    @ResponseBody
    public String checkMoney(String uName, String hour, double zmoney, HttpSession session) {
        UserB userB = (UserB) session.getAttribute("user");
        Integer uid = userB.getId();//用户id
        Object pids = session.getAttribute("id");//shop商品id
        int pid = (int) pids;

        boolean flag = false;
        UserB ub = userService.getUserg(uName);
        if (ub.getGold() < zmoney) {
            return JSON.toJSONString(flag);
        } else {
            //实现添加
            Integer hours = 1;
            if (hour != null) {
                hours = Integer.parseInt(hour);//租用时间
                userService.addUserOrder(uid, pid, hours, zmoney);
            }

            return JSON.toJSONString(ub.getGold() - zmoney);
        }
    }

    @RequestMapping("/ShowServlet")
    @ResponseBody
    public String ShowServlet(HttpSession session,Integer pageNumber) {
        Integer id = (Integer) session.getAttribute("id");
        Shop shop = userService.getShop(id);
        pageNumber = pageNumber == null ? 1 : pageNumber;
        //Integer id = (Integer) session.getAttribute("id");

        //Shop shop = userService.getShop(id);
        //每页显示多少条
        Integer pageSize = 3;

        //根据ID查询shop的评论
        /*List<Comment>  comments = commentService.getComment(id);*/
        PageBeanHelper<Comment> comments = commentService.getComment(id, pageNumber, pageSize);

        shop.setCommentPages(comments);

        return JSON.toJSONString(shop);
    }


    @RequestMapping("/Select_to_showServlet")
    @ResponseBody
    public String Select_to_showServlet(Integer id, HttpSession session) {
        session.setAttribute("id", id);

        return JSON.toJSONString(id);
    }


    @RequestMapping("/TuiServlet")
    @ResponseBody
    public String TuiServlet(HttpSession session) {
        session.removeAttribute("user");
        return JSON.toJSONString(" ");
    }

    @RequestMapping("/getGold")
    @ResponseBody
    public String getGole(Integer id) {
        int gold = userService.getGold(id);
        return JSON.toJSONString(gold);
    }


    @RequestMapping("/updataAddMoney")
    @ResponseBody
    public String updataAddMoney(String uName, double gold) {
        boolean flag = userService.cMoney(uName, gold);
        return JSON.toJSONString(flag);
    }

    @RequestMapping("/deleteShop")
    @ResponseBody
    public String deleteShop(Integer id) {
        boolean flag = userService.deleteShop(id);
        return JSON.toJSONString(flag);
    }


    @RequestMapping("/updateShop")
    @ResponseBody
    public String updateShop(Shop shop) {
        boolean flag = userService.updateShop(shop);
        return JSON.toJSONString(flag);
    }


    @RequestMapping("/getShopCount")
    @ResponseBody
    public String getShopCount(Integer id) {
        Integer totalCount = userService.getShopCount(id);
        return JSON.toJSONString(totalCount);
    }


    @RequestMapping("/getShopList")
    @ResponseBody
    public String getShopList(Integer currentPage, Integer id, Integer pageSize) {
        Integer page = (currentPage - 1) * pageSize;
        UserB userB = userService.getShopList(page, pageSize, id);
        return JSON.toJSONString(userB);
    }


    @RequestMapping("/checkShopList")
    @ResponseBody
    public String checkShopList(Integer id) {
        boolean flag = userService.checkShop(id);
        return JSON.toJSONString(flag);

    }


    @RequestMapping("/Center_fbAddServlet")
    @ResponseBody
    public String Center_fbAddServlet(Shop shop) {
        System.out.println(shop.toString());
        boolean flag = userService.addShop(shop);
        return JSON.toJSONString(flag);
    }


    @RequestMapping("/selectUserCenterServlet")
    @ResponseBody
    public String selectUserCenterServlet(HttpSession session) {
        String uName = null;
        UserB userb = (UserB) session.getAttribute("user");
        uName = userb.getuName();
        if (uName != null) {
            UserB u = userService.getUserg(uName);
            return JSON.toJSONString(u);
        } else {
            return JSON.toJSONString(false);
        }
    }

    //查找游戏名方法
    @RequestMapping("/Center_fbServlet")
    @ResponseBody
    public String Center_fbServlet() {
        List<GameNum> gameNums = userService.gnList();
        return JSON.toJSONString(gameNums);
    }


    @RequestMapping("/IndexServlet")
    @ResponseBody
    public String IndexServlet(HttpSession session) {
        UserB userB = (UserB) session.getAttribute("user");
        return JSON.toJSONString(userB.getuName());
    }


    @RequestMapping("/register")
    @ResponseBody
    public String register(UserB userB) {
        String flag = "false";
        if (userService.userAdd(userB)) {
            flag = "true";
        }
        return JSON.toJSONString(flag);
    }


    @RequestMapping("/zfb/{money},{zgold},{uName}")
    public String zfb(@PathVariable String money, @PathVariable String zgold, @PathVariable String uName, HttpSession session) {
        System.out.println(zgold);
        int moneyn = Integer.valueOf(money);
        Double zgoldn = Double.valueOf(zgold);
        session.setAttribute("money1", moneyn);
        session.setAttribute("zgold1", zgoldn);
        session.setAttribute("uName1", uName);

        //添加数据
        UserB user = (UserB) session.getAttribute("user");
        int row = userService.upDateMoney(zgoldn, user.getId());

        return "index1";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String userName, String pwd, HttpSession session) {
        UserB userB = userService.login(userName, pwd);
        session.setAttribute("user", userB);
        session.setAttribute("userName", userB.getuName());
        String flag = "";
        if (userB != null) {
            flag = "true";
        } else {
            flag = "false";
        }
        return JSON.toJSONString(flag);
    }


}
